package com.jeasy.validate;

import java.lang.reflect.Field;

import org.springframework.stereotype.Service;

import com.jeasy.AnnotationValidable;
import com.jeasy.GetFiledValue;
import com.jeasy.Handler;
import com.jeasy.ValidateException;

import lombok.extern.slf4j.Slf4j;

/**
 * Validate the @ValidateSize annotation
 *
 * @author taomk
 * @version 1.0
 * @since 2014/10/20 15:44
 */
@Slf4j
@Service("validateSizeHandler")
public class ValidateSizeHandler implements Handler {

	public void validate(AnnotationValidable validatedObj, Field field) throws ValidateException {
		log.info(this.getClass().getName(), "validate()");

		if (field.isAnnotationPresent(ValidateSize.class)) {
			checkSize(validatedObj, field);
		}

		log.info(this.getClass().getName(), "validate()");
	}

	/**
	 * validate the String length
	 * 
	 * @param filter
	 *            filter validated object
	 * @param field
	 *            validated field or property
	 * @throws ValidateException
	 */
	private void checkSize(AnnotationValidable filter, Field field) throws ValidateException {
		log.info(this.getClass().getName(), "checkSize()");

		ValidateSize annotation = field.getAnnotation(ValidateSize.class);
		String minSize = annotation.minSize();
		String maxSize = annotation.maxSize();
		String message = annotation.message();
		int min = 0;
		int max = 0;
		if (!"".equals(minSize)) {
			min = Integer.parseInt(minSize);
		}
		if (!"".equals(maxSize)) {
			max = Integer.parseInt(maxSize);
		}
		String value;
		try {
			value = (String) GetFiledValue.getField(filter, field.getName());
		} catch (Exception ex) {
			log.info("Get field value or cast value error. Error message: " + ex.getMessage(), ex);
			throw new ValidateException(ex.getMessage(), ex);
		}
		int size = 0;
		if (!"".equals(value) && value != null) {
			size = value.length();
		}
		if (!"".equals(minSize) && !"".equals(maxSize)) {
			if (size < min || size > max) {
				log.info("Validate fail. Error message: validate size is:" + size + ",minSize value is:" + min + ",maxSize value is:" + max);
				throw new ValidateException(message + "The size is:" + size + ",The min size should is:" + min + ",the max size should is:" + max);
			}
		}
		if (!"".equals(minSize) && "".equals(maxSize)) {
			if (size < min) {
				log.info("Validate fail. Error message: validate size is:" + size + ",minSize value is:" + min);
				throw new ValidateException(message + "The size is:" + size + ",The min size should is:" + min);
			}
		}
		if ("".equals(minSize) && !"".equals(maxSize)) {
			if (size > max) {
				log.info("Validate fail. Error message: validate size is:" + size + ",maxSize value is:" + max);
				throw new ValidateException(message + "The size is:" + size + ",The max size should is:" + max);
			}
		}

		log.info(this.getClass().getName(), "checkSize()");
	}
}
